package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.common.kafka.constant.KafkaConst;
import com.atguigu.tingshu.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * 专辑上下架Kafka消费者监听器
 */
@Slf4j
@Component
public class AlbumKafkaListener {

    @Autowired
    private SearchService searchService;

    /**
     * 消费专辑上架消息
     *
     * @param record 消息记录
     * @param ack    手动确认对象
     */
    @KafkaListener(topics = KafkaConst.TOPIC_ALBUM_UPPER, groupId = KafkaConst.GROUP_SEARCH)
    public void handleAlbumUpper(ConsumerRecord<String, String> record, Acknowledgment ack) {
        try {
            String albumIdStr = record.value();
            Long albumId = Long.parseLong(albumIdStr);

            log.info("收到专辑上架消息 - albumId: {}, Topic: {}, Partition: {}, Offset: {}",
                    albumId,
                    record.topic(),
                    record.partition(),
                    record.offset());

            // 调用上架服务
            searchService.upperAlbum(albumId);

            // 手动确认消息
            ack.acknowledge();
            log.info("专辑上架成功 - albumId: {}", albumId);

        } catch (Exception e) {
            log.error("处理专辑上架消息失败 - Message: {}, Error: {}",
                    record.value(), e.getMessage(), e);
            // 发生异常时也确认消息，避免重复消费
            // 如果需要重试，可以将消息发送到死信队列
            ack.acknowledge();
        }
    }

    /**
     * 消费专辑下架消息
     *
     * @param record 消息记录
     * @param ack    手动确认对象
     */
    @KafkaListener(topics = KafkaConst.TOPIC_ALBUM_LOWER, groupId = KafkaConst.GROUP_SEARCH)
    public void handleAlbumLower(ConsumerRecord<String, String> record, Acknowledgment ack) {
        try {
            String albumIdStr = record.value();
            Long albumId = Long.parseLong(albumIdStr);

            log.info("收到专辑下架消息 - albumId: {}, Topic: {}, Partition: {}, Offset: {}",
                    albumId,
                    record.topic(),
                    record.partition(),
                    record.offset());

            // 调用下架服务
            searchService.lowerAlbum(albumId);

            // 手动确认消息
            ack.acknowledge();
            log.info("专辑下架成功 - albumId: {}", albumId);

        } catch (Exception e) {
            log.error("处理专辑下架消息失败 - Message: {}, Error: {}",
                    record.value(), e.getMessage(), e);
            // 发生异常时也确认消息，避免重复消费
            // 如果需要重试，可以将消息发送到死信队列
            ack.acknowledge();
        }
    }
}
